package com.yanxu.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yanxu.entity.User;
import com.yanxu.mapper.UserMapper;
import jakarta.annotation.Resource;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsPasswordService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.provisioning.UserDetailsManager;

import java.util.ArrayList;
import java.util.Collection;

/**
 * @author 折戟沉沙铁未销
 * @version V1.0
 * @date 2025-10-10-2025
 * @Description: DBUserDetailManager 自定义基于数据库的 用户管理器
 */
public class DBUserDetailManager implements UserDetailsManager, UserDetailsPasswordService {

    @Resource
    private UserMapper userMapper;

    /*
     * loadUserByUsername 该方法的本质作用是 “根据 username 查询对应的用户信息”
     *
     * 重写该方法，基于数据库作为数据源
     *  从数据库中根据用户名查询用户信息
     * */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //从数据库中查询用户对象
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        User user = userMapper.selectOne(queryWrapper);
        //校验用户
        if (user == null) {
            throw new RuntimeException("该用户不存在!!!");
        } else{
            //将 我们自己的  com.yanxu.User  转换为 springsecurity 框架需要的 UserDetails 对象
            Collection<GrantedAuthority>  grantedAuthorities = new ArrayList<>();
            return new org.springframework.security.core.userdetails.User(
                    user.getUsername(),
                    user.getPassword(),
                    user.getEnabled(),
                    true,//用户账号是否未过期
                    true, //用户凭证是否过期
                    true, //用户是否未被锁定
                    grantedAuthorities  //权限列表
            );
        }
    }

    /**
     * 向数据库中插入用户信息
     * @param userDetails
     */
    @Override
    public void createUser(UserDetails userDetails) {
        User user = new User();
        user.setUsername(userDetails.getUsername());
        user.setPassword(userDetails.getPassword());
        user.setEnabled(userDetails.isEnabled());
        userMapper.insert(user);
    }

    /**
     * 更新用户信息
     * @param user
     */
    @Override
    public void updateUser(UserDetails user) {

    }

    /**
     * 修改用户密码信息
     * @param user
     * @param newPassword
     * @return
     */
    @Override
    public UserDetails updatePassword(UserDetails user, String newPassword) {
        return null;
    }

    /**
     * 删除用户信息
     * @param username
     */
    @Override
    public void deleteUser(String username) {

    }

    @Override
    public void changePassword(String oldPassword, String newPassword) {

    }

    @Override
    public boolean userExists(String username) {
        return false;
    }


}